'use strict';

/* main controller */
angular.module('app').controller('AppCtrl', function ($scope, ajax, $translate,
    $localStorage, $rootScope, authorities, hanMsg, $state, $window, $modal, $q, toaster, cos) {

    function isSmartDevice($window) {
        var ua = $window['navigator']['userAgent'] || $window['navigator']['vendor'] || $window['opera'];
        return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
    }
    // add 'ie' classes to html
    if (!!navigator.userAgent.match(/MSIE/i)) angular.element($window.document.body).addClass('ie');
    if (isSmartDevice($window)) angular.element($window.document.body).addClass('smart');

    // config
    $scope.app = {
        name: 'hbglky',
        version: '1.3.3',
        // for chart colors
        color: {
            primary: '#7266ba',
            info: '#23b7e5',
            success: '#27c24c',
            warning: '#fad733',
            danger: '#f05050',
            light: '#e8eff0',
            dark: '#3a3f51',
            black: '#1c2b36'
        },
        settings: {
            themeID: 8,
            navbarHeaderColor: 'bg-white',
            navbarCollapseColor: 'bg-white',
            asideColor: 'bg-black b-r',
            headerFixed: true,
            asideFixed: false,
            asideFolded: false,
            asideDock: false,
            container: false
        }
    };

    // 状态开始，访问权限过滤
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        fromState.params = fromParams;
        $state.previous = fromState;
        var authority = toState.authority;
        if (authority && !authorities.hasAuthority(authority)) {
            event.preventDefault();
            $rootScope.$state.go('access.signin');
        }
    });
    /* jshint unused:false */
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        fromState.params = fromParams;
        $state.previous = fromState;
        if (toState.name.indexOf("access") >= 0) return;	//前台
        if (!$rootScope.$state.isLogin) {	//后台
            event.preventDefault();
            $rootScope.$state.go("access.signin");
        }
    });
    /* jshint unused:true */
    $scope.forceFrash = function () { //强制刷新，获取登陆对象
        var uri = 'staff/{username}/forceFrash'.format({
            username: $rootScope.loginUser.username
        });
        ajax.get(uri, function (result) {
            if (result && result.code == 200) {
                $scope.$apply($rootScope.loginUser = result.result);
            } else {
                $rootScope.$state.go('access.signin');
            }
        }, function () { });
    };

    $scope.logout = function () {
        var userid = $rootScope.loginUser.id;
        var uri = 'staff/{userid}/logout'.format({ userid: userid });
        $rootScope.loginUser = null;
        $rootScope.$state.isLogin = false;
        ajax.get(uri, function () {
            $rootScope.$state.go("access.signin");
        }, function () {
            $rootScope.$state.go("access.signin");
        });
    };

    $scope.loadConfig = function () {
        ajax.get('/configuration', function (data) {
            if (data.code == 200) cos.init(data.result);
        }, function () { });
    };
    $scope.loadConfig();

    // save settings to local storage
    if (angular.isDefined($localStorage.settings)) {
        $scope.app.settings = $localStorage.settings;
    } else {
        $localStorage.settings = $scope.app.settings;
    }
    $scope.$watch('app.settings', function () {
        if ($scope.app.settings.asideDock)
            $scope.app.settings.headerFixed = $scope.app.settings.asideFixed;
        // save to local storage
        $localStorage.settings = $scope.app.settings;
    }, true);

    // angular translate
    $scope.lang = { isopen: false };
    $scope.langs = { en: 'English', de_DE: 'German', it_IT: 'Italian', zh_cn: 'Chinese' };
    $scope.selectLang = $scope.langs[$translate.proposedLanguage()] || "English";
    $scope.setLang = function (langKey, $event) { /* jshint unused:false */
        // set the current lang
        $scope.selectLang = $scope.langs[langKey];
        // You can change the language during runtime
        $translate.use(langKey);
        $scope.lang.isopen = !$scope.lang.isopen;
    };

    //session失效
    $rootScope.$on('userIntercepted', function (event, errorType) {
        if (errorType && (errorType == "sessionTimeout" || errorType == "notAuthenticated")) {
            $rootScope.loginUser = null;
            $rootScope.$state.isLogin = false;
            $rootScope.$state.go('access.signin', {
                from: $rootScope.$state.current.name,
                w: errorType
            });
        }
    });

    $rootScope.notifyMsg = { list: [], unread: 0 };
    $scope.allRead = function () {  // 所有消息已读
        var userid = $rootScope.loginUser.id;
        var uri = 'notify/{userid}/read/all'.format({ userid: userid });
        ajax.call(new Req.POST({ resource: uri }))
            .then(function (result) {
                if (result.code == 200 && result.code >= 0) {
                    $rootScope.notifyMsg.list = [];
                    $rootScope.notifyMsg.unread = 0;
                    $scope.loadUnreadNotify(userid);
                }
            }, function () { });
    };

    // 加载未读消息
//    $rootScope.loadUnreadNotify = function (userid) {
//        var unread = 'notify/{userid}/unread'.format({ userid: userid });
//        ajax.get(unread, function (result) {
//            if (result.code && result.code == 200) {
//                $rootScope.notifyMsg.list = result.result;
//                $rootScope.notifyMsg.unread = result.result.length;
//            }
//        }, function () { });
//    };

    // 加载代售点二维码信息
//    $scope.agencyQr = "";
//    $scope.loadAgencyQr = function () {
//        var uri = 'agency/{userid}/qr'.format({ userid: $rootScope.loginUser.id });
//        ajax.get(uri, function (result) {
//            if (result.code == 200) $scope.agencyQr = result.result;
//        }, function () { });
//    };

    // 监听web socket推送消息
    var listenNotify = function () {
        var received = function (data) {
            var msg = JSON.parse(data.body);
            $scope.$apply(function () {
                $rootScope.notifyMsg.list.push(msg);
                $rootScope.notifyMsg.unread++;
            });
        };
        hanMsg.subscribe('/notify/' + $rootScope.loginUser.username, received);
        hanMsg.subscribe('/broadcast', received);
        hanMsg.send('/default', { user: $rootScope.loginUser.username, message: 'user online' });
    };

    // 处理用户已登录事件
    $scope.$on('user.login', function (event, data) {
        $rootScope.loadUnreadNotify(data.uid);
        hanMsg.initialize({ onconnect: listenNotify });
        $scope.loadAgencyQr();
    });
    if ($rootScope.$state.isLogin) {
        $rootScope.loadUnreadNotify($rootScope.loginUser.id);
        hanMsg.initialize({ onconnect: listenNotify });
        $scope.loadAgencyQr();
    }

    $rootScope.serverError = function () { toaster.pop("error", "连接错误", "与服务器的连接失败！"); };
    // 菜单页的数据记录参数
    $rootScope.maxSize = 10;            // 每页记录数
    $rootScope.bigTotalItems = 0;       // 记录总数
    $rootScope.bigCurrentPage = 1;      // 当前页数
    $rootScope.dataList = [];
    $rootScope.delModal = function (size, current_data, submit_type) {
        $rootScope.current_data = angular.copy(current_data);
        return $modal.open({
            templateUrl: 'template/deleteModal.html?v=01e7f8821f',
            controller: 'ModalCtrl',
            size: size,
            resolve: {
                param: function () {
                    return {
                        "data": $rootScope.current_data,
                        "type": submit_type
                    };
                }
            }
        });
    };
    $rootScope.page = {     // 封装通用的分页查询、新增、修改和删除方法
        url: '',
        loader: function (url) {
            this.url = url;
            $rootScope.maxSize = 20;            // 每页记录数
            $rootScope.pageSize = 0;            // 当前页记录数
            $rootScope.bigTotalItems = 0;       // 记录总数
            $rootScope.bigCurrentPage = 1;      // 当前页数
            $rootScope.dataList = [];
            return function (param, queryMap) {
                var querier;
                if (typeof (param) === "number") {
                    querier = new Req.GET();
                    querier.page_index = param;
                    if (queryMap) querier.params = queryMap;
                } else if (typeof (param) === "object") {
                    querier = param;
                } else {
                    return;
                }
                querier.resource = url.format({ pageIndex: querier.page_index, pageSize: $rootScope.maxSize });
                ajax.call(querier).then(function (result) {
                    if (result.code && result.code == 200) {
                        $rootScope.bigTotalItems = result.totalCount;
                        $rootScope.bigCurrentPage = result.pageNumber;
                        $rootScope.dataList = result.result;
                        $rootScope.pageSize = $rootScope.dataList.length;
                    } else {
                        if (result.code == 423) {
                            toaster.pop('warning', '提醒', result.result);
                        } else {
                            $rootScope.dataList = [];
                            $rootScope.pageSize = 0;
                        }
                    }
                }, function () {
                    $rootScope.dataList = [];
                    $rootScope.pageSize = 0;
                });
            };
        },
        add: function (inserter, reload, queryMap) {
            var deferred = $q.defer();
            ajax.call(inserter).then(function (result) {
                if (result.code == 200) {
                    toaster.pop('success', '成功', '新增信息成功。');
                    if (reload) reload(1, queryMap);
                    deferred.resolve(result);
                } else if (result.code == 423) {
                } else {
                    toaster.pop('error', '错误', result.result);
                    deferred.reject(result);
                }
            }, function (result) {
                toaster.pop('error', '连接错误', '与服务器的连接失败！');
                deferred.reject(result);
            });
            return deferred.promise;
        },
        mod: function (updater, reload, queryMap) {
            var deferred = $q.defer();
            ajax.call(updater).then(function (result) {
                if (result.code == 200) {
                    toaster.pop('success', '成功', '修改信息成功。');
                    if (reload) reload($rootScope.bigCurrentPage, queryMap);
                    deferred.resolve(result);
                } else if (result.code == 423) {
                } else {
                    toaster.pop('error', '错误', result.result);
                    deferred.reject(result);
                }
            }, function (result) {
                toaster.pop('error', '连接错误', '与服务器的连接失败！');
                deferred.reject(result);
            });
            return deferred.promise;
        },
        del: function (deleter, reload, queryMap) {
            var deferred = $q.defer();
            ajax.call(deleter).then(function (result) {
                if (result.code == 200) {
                    toaster.pop('success', '成功', '删除信息成功。');
                    if (reload) reload($rootScope.bigCurrentPage, queryMap);
                    deferred.resolve(result);
                } else if (result.code == 423) {
                } else {
                    toaster.pop('error', '错误', result.result);
                    deferred.reject(result);
                }
            }, function (result) {
                toaster.pop('error', '连接错误', '与服务器的连接失败！');
                deferred.reject(result);
            });
            return deferred.promise;
        },
    };
});